package hu.myai.util.db;

import hu.myai.model.db.AxHistory;

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class QueryAsxHistoryData {

    /**
     * The object used when logging debug,errors,warnings and info.
     * */
    private final Logger log = LoggerFactory.getLogger(this.getClass());

    private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("MyAI");
    private EntityManager entityManager = emf.createEntityManager();

    /**
     * get a list of data from the asx database
     * */
    @SuppressWarnings("unchecked")
    public List<AxHistory> getSavedHistoryList(Date date, String symbol, int maxSize) {

        // set the date as early as possible
        if (date == null) {
            date = new Date(0);
        }

        try {
            // get the history from the database
            return entityManager
                    .createQuery(
                            "select h from hu.myai.model.db.AxHistory h where h.date > :date and h.symbol = :symbol order by date")
                    .setParameter("date", date).setParameter("symbol", symbol).setMaxResults(maxSize).getResultList();

        } catch (RuntimeException ex) {
            log.debug("Error - getSavedHistory - not a single history records: " + ex.getMessage());
            return null;
        }
    }
}
